package io.nick.reqenhance.utils;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.nick.reqenhance.exception.JsonParsingException;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

/**
 * Jackson 序列化,反序列化工具类
 *
 * @author Nick
 * @date 2019-07-09 06:00
 */
@Slf4j
public class JacksonUtils {

  private static final ObjectMapper MAPPER = new ObjectMapper();

  public static ObjectMapper getInstance() {
    return MAPPER;
  }

  /**
   * 转换为 JSON 字符串
   *
   * @param obj 要转换的对象
   * @return 转换后的JSON串
   */
  public static String obj2json(Object obj) {
    try {
      return MAPPER.writeValueAsString(obj);
    } catch (JsonProcessingException e) {
      log.error(e.getMessage());
      throw new JsonParsingException(e.getMessage());
    }
  }

  /**
   * 转换为 JSON 字符串，忽略空值
   *
   * @param obj 要转换的对象
   * @return 转换后的JSON串
   */
  public static String obj2jsonIgnoreNull(Object obj) {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    try {
      return mapper.writeValueAsString(obj);
    } catch (JsonProcessingException e) {
      log.error(e.getMessage());
      throw new JsonParsingException(e.getMessage());
    }
  }

  /**
   * 转换为 JavaBean
   *
   * @param jsonString 待转换的JSON串
   * @param clazz 待转换的Java全限定类型
   * @return JavaBean
   */
  public static <T> T json2pojo(String jsonString, Class<T> clazz) {
    MAPPER.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
    try {
      return MAPPER.readValue(jsonString, clazz);
    } catch (IOException e) {
      log.error(e.getMessage());
      throw new JsonParsingException(e.getMessage());
    }
  }

  /**
   * 字符串转换为 Map<String, Object>
   *
   * @param jsonString JSON串
   * @return Map映射
   */
  @SuppressWarnings("unchecked")
  public static Map<String, Object> json2map(String jsonString) {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    try {
      return mapper.readValue(jsonString, Map.class);
    } catch (IOException e) {
      log.error(e.getMessage());
      throw new JsonParsingException(e.getMessage());
    }
  }

  /**
   * 字符串泛型转换为 Map<String, T>
   *
   * @param jsonString JSON串
   * @return Map映射
   */
  public static <T> Map<String, T> json2map(String jsonString, Class<T> clazz) {
    Map<String, Map<String, Object>> map;
    try {
      map = MAPPER.readValue(jsonString, new TypeReference<Map<String, T>>() {});
    } catch (IOException e) {
      log.error(e.getMessage());
      throw new JsonParsingException(e.getMessage());
    }
    Map<String, T> result = new HashMap<>();
    for (Map.Entry<String, Map<String, Object>> entry : map.entrySet()) {
      result.put(entry.getKey(), map2pojo(entry.getValue(), clazz));
    }
    return result;
  }

  /**
   * 递归解析 JSON 成 Map
   *
   * @param json JSON串
   * @return Map映射
   */
  public static Map<String, Object> json2mapDeeply(String json) {
    return json2MapRecursion(json);
  }

  /**
   * 把 JSON 解析成 向量，如果 向量 内部的元素存在 jsonString，继续解析
   *
   * @param json JSON串
   * @return 返回一个向量
   */
  @SuppressWarnings("unchecked")
  private static List<Object> json2ListRecursion(String json) {
    if (json == null) {
      return null;
    }

    List<Object> list;
    try {
      list = MAPPER.readValue(json, List.class);
    } catch (IOException e) {
      log.error(e.getMessage());
      throw new JsonParsingException(e.getMessage());
    }

    for (Object obj : list) {
      if (obj instanceof String) {
        String str = (String) obj;
        if (str.startsWith("[")) {
          json2ListRecursion(str);
        } else if (obj.toString().startsWith("{")) {
          json2MapRecursion(str);
        }
      }
    }

    return list;
  }

  /**
   * 把 JSON 解析成 Map，如果 Map 内部的 Value 存在 jsonString，继续解析
   *
   * @param json JSON串
   * @return 深度解析后的Map映射
   */
  @SuppressWarnings("unchecked")
  private static Map<String, Object> json2MapRecursion(String json) {
    try {
      if (json == null) {
        return null;
      }

      Map<String, Object> map = MAPPER.readValue(json, Map.class);

      for (Entry<String, Object> entry : map.entrySet()) {
        Object obj = entry.getValue();
        if (obj instanceof String) {
          String str = ((String) obj);

          if (str.startsWith("[")) {
            List<?> list = json2ListRecursion(str);
            map.put(entry.getKey(), list);
          } else if (str.startsWith("{")) {
            Map<String, Object> mapRecursion = json2MapRecursion(str);
            map.put(entry.getKey(), mapRecursion);
          }
        }
      }
      return map;
    } catch (Exception e) {
      log.error(e.getMessage());
      throw new JsonParsingException(e.getMessage());
    }
  }

  /**
   * 将 JSON 数组转换为向量
   *
   * @param jsonArrayStr json数组
   * @param clazz 待转换的数组内对象
   * @return 返回向量
   */
  public static <T> List<T> json2list(String jsonArrayStr, Class<T> clazz) {
    JavaType javaType = getCollectionType(ArrayList.class, clazz);
    try {
      return MAPPER.readValue(jsonArrayStr, javaType);
    } catch (IOException e) {
      log.error(e.getMessage());
      throw new JsonParsingException(e.getMessage());
    }
  }

  /**
   * 获取泛型的 Collection Type
   *
   * @param collectionClass 泛型的Collection
   * @param elementClasses 元素类
   * @return JavaType Java类型
   */
  public static JavaType getCollectionType(Class<?> collectionClass, Class<?>... elementClasses) {
    return MAPPER.getTypeFactory().constructParametricType(collectionClass, elementClasses);
  }

  /**
   * 将 Map 转换为 JavaBean
   *
   * @param map 待转换的Map映射
   * @param clazz 待转换的Java全限定类名
   * @return 转换后的Java对象
   */
  public static <T> T map2pojo(Map map, Class<T> clazz) {
    return MAPPER.convertValue(map, clazz);
  }

  /**
   * 将 Map 转换为 JSON
   *
   * @param map 待解析的Map映射
   * @return JSON串
   */
  public static String mapToJson(Map map) {
    try {
      return MAPPER.writeValueAsString(map);
    } catch (JsonProcessingException e) {
      log.error(e.getMessage());
      throw new JsonParsingException(e.getMessage());
    }
  }

  /**
   * 将 JSON 对象转换为 JavaBean
   *
   * @param obj 待解析的Java对象
   * @param clazz 全限定类名
   * @return Java对象
   */
  public static <T> T obj2pojo(Object obj, Class<T> clazz) {
    return MAPPER.convertValue(obj, clazz);
  }
}
